package com.panshi.controller.qiniu;

import com.panshi.qiniuyun.QiniuUtils;
import com.panshi.qiniuyun.UploadImageImp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@Controller
@RequestMapping("/qiniu")
public class QiniuController {

    @Resource
    private UploadImageImp uploadImageImp;

    @GetMapping("/test")
    public ModelAndView test(){

        return new ModelAndView("qiniu/qiniuText");
    }

    @PostMapping("/upload")
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile file) throws IOException {

        //获取文件的名称
        String fileName = file.getOriginalFilename();

        //使用工具类根据上传文件生成唯一的图片名称
        String imgName = QiniuUtils.getRandomImgName(fileName);

        log.info("--------------------------------fileName:{}",fileName);
        log.info("--------------------------------imgName:{}",imgName);

        if(!file.isEmpty()){

            FileInputStream stream = (FileInputStream) file.getInputStream();

            String path = uploadImageImp.uploadQNImg(stream,imgName);

            path = "http://"+path;

            log.info("七牛云返回的图片链接*****************：{}",path);

            return path;
        }
        return "上传失败";
    }

}
